<template>
    <div class="container" id="Create">
        <div class="create-title">
            <h3>创建菜单</h3>
        </div>
        <form method="post" class="create-menu">
            <input type="text" maxlength="30" v-model="menu.menuFatherName" class="menu-title" placeholder="菜单名称(必填，30字以内)">
            <textarea class="menu-introduce" v-model="menu.menuFatherIntroduce" placeholder="菜单介绍"></textarea>
            <div class="menu-list">
                <div class="create-title">
                    <h3>
                        添加菜谱
                        <p class="spclie">(填入美食的食谱ID，如http://localhost:8081/DishDetails/109即食谱ID为109)</p>
                    </h3>
                </div>
                <input type="text" @click="addOne(index)" @blur="blurFun(index)" placeholder="请输入菜品id" v-for="(data,index) in menu.list" v-model="menu.list[index]" :key="index">
            </div>
            <span class="menu-add" @click="addItem()">添加</span>
            <div class="menu-img">
                <input type="file" accept="image/*" @change="showImg()" ref="img">
                <img v-if="imgUpload.imgShow" :src="imgUpload.imgSrc" alt="">
                <div v-if="imgUpload.uploading">正在上传</div>
                <i class="el-icon-refresh menu-refresh" @click="changeImg()"></i>
            </div>
            <div class="menu-code">
                <span>验证码：</span>
                <input type="text" v-model="imputCode">
                <div class="code" @click="refreshCode">
                    <s-identify :fresh="flag" @makedCode="getMakedCode"></s-identify>
                </div>
            </div>
            <span class="menu-submit" @click="submitFun()">提交</span>
        </form>
    </div>
</template>
<script>
import cookie from '../../../cookien'
import SIdentify from '../home/tool/SIdentify.vue'
export default {
  name: 'Create',
  components: { SIdentify },
  data () {
    return {
      flag: true,
      code: '',
      imputCode: '',
      imgUpload: {
        imgShow: false,
        uploading: false,
        imgSrc: null
      },
      menu: {
        list: [''],
        menuFatherSrc: '',
        menuFatherName: '',
        menuFatherIntroduce: ''
      },
      fullscreenLoading: false
    }
  },
  mounted () {
    this.flag = !this.flag
  },
  methods: {
    showImg () {
      console.log(this)
      var that = this
      console.log(this.$refs.img.files)
      var f = new FileReader()
      f.readAsDataURL(this.$refs.img.files[0])
      that.menu.menuFatherSrc = this.$refs.img.files[0]
      f.onload = function () {
        that.imgUpload.imgSrc = f.result
      }
      that.imgUpload.imgShow = true
    },
    changeImg () {
      this.$refs.img.dispatchEvent(new MouseEvent('click'))
    },
    addItem () {
      this.menu.list.push('')
    },
    addOne (index) {
      if (index === this.menu.list.length - 1) {
        this.menu.list.push('')
      }
    },
    blurFun (index) {
      this.menu.list[index] = this.menu.list[index].replace(/\s*/g, '')
      if (this.menu.list[index].length !== 0) {
        if (Number.isInteger(parseInt(this.menu.list[index]))) {
          this.$axios({
            method: 'POST',
            url: '/Menu/Visitor/findMenuById',
            params: {
              menuId: this.menu.list[index]
            },
            headers: {
              token: cookie.getToken()
            }
          }).then(data => {
            if (data.data.code === 200) {
            } else {
              this.$message.error('抱歉未找到改食谱，请重试')
              this.$set(this.menu.list, index, '')
            }
            console.log(data.data)
          }).catch(error => {
            console.log(error)
          })
        } else {
          this.$message('食谱id应为数字，请重试')
          this.$set(this.menu.list, index, '')
        }
      } else {
        console.log('123')
      }
    },
    submitFun () {
      if (this.judgeFun()) {
        const file = this.$refs.img.files[0]
        if (file === undefined) {
          this.$message('请选择封面图')
          return false
        }
        const param = new FormData()
        const arrlist = []
        for (let i = 0; i < (this.menu.list.length - 1); i++) {
          if (arrlist.indexOf(this.menu.list[i]) === -1) {
            if (this.menu.list[i] !== '') {
              arrlist.push(this.menu.list[i])
            }
          }
        }
        if (arrlist.length === 0) {
          this.$message('请添加菜谱')
          return false
        }
        const str = arrlist.join(',')
        param.append('menuFatherSrc', file)
        param.append('userId', this.$store.state.userMsg.userId)
        param.append('menuIds', str)
        param.append('menuFatherName', this.menu.menuFatherName)
        param.append('menuFatherIntroduce', this.menu.menuFatherIntroduce)
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: cookie.getToken()
          }
        }
        const loading = this.$loading({
          lock: true,
          text: '菜单上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.6)'
        })
        this.$axios.post('Menu/User/addMenuFather', param, config)
          .then(res => {
            console.log(res)
            if (res.data.code === 200) {
              this.$message({
                message: '菜单以上传至平台，审核通过后即可查看，请耐心等待',
                type: 'success'
              })
              this.menu.list = ['']
              this.menu.menuFatherSrc = ''
              this.menu.menuFatherName = ''
              this.menu.menuFatherIntroduce = ''
              this.imputCode = ''
              this.imgUpload.imgSrc = null
              this.imgUpload.imgShow = false
              this.$refs.img.value = ''
              loading.close()
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    refreshCode () {
      this.flag = !this.flag
    },
    getMakedCode (code) {
      this.code = code
      console.log('getMakedCode:', this.code)
    },
    judgeFun () {
      if (this.menu.menuFatherName.trim() === '') {
        this.$message('请填写菜单名称')
        return false
      } else if (this.menu.menuFatherIntroduce.trim() === '') {
        this.$message('请填写菜谱介绍')
        return false
      } else if (this.imputCode.trim() === '') {
        this.$message('请填写验证码')
        return false
      } else {
        if (this.imputCode === this.code) {
          return true
        } else {
          this.$message.error('验证码错误请重试')
          return false
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container{
    width: 1000px;
    margin: 60px auto;
    height:auto;
    .create-title{
        line-height:78px;height:78px;
        text-align:left;
        h3{
            font-size:18px;
            p{
                display:inline-block;
                font-size: 16px;
                color: red;
                font-weight:600;
            }
        }
    }
    .create-menu{
        width: 100%;
        // padding-top: 60px;
        text-align:left;
        input{
            display: block;
            width: 690px;height: 42px;
            line-height:42px;
            border: 1px solid #E5E3DF;
            padding:0 12px;
            border-radius: 4px;
            font-size: 15px;
        }
        .menu-introduce{
            width: 690px;height: 170px;margin-top: 30px;
            border: 1px solid #E5E3DF;
            padding: 12px;
            border-radius: 4px;resize: none;
            font-size: 15px;
        }
        input::-webkit-input-placeholder, textarea::-webkit-input-placeholder{
           font-size:15px;
           color: rgba(0,0,0,0.7);
        }/*webkit 内核浏览器*/
         input::-moz-placeholder, textarea:-moz-placeholder{
           font-size:15px;
           color: rgba(0,0,0,0.7);
        }/*Mozilla Firefox 19+*/
         input:-moz-placeholder, textarea:-moz-placeholder{
           font-size:15px;
           color: rgba(0,0,0,0.7);
        }/*Mozilla Firefox 4 to 18*/
        input:-ms-input-placeholder, textarea:-ms-input-placeholder{
          font-size:15px;
          color: rgba(0,0,0,0.7);
        }/*Internet Explorer 10+*/
        .menu-list{
            input{
                margin: 0 0 20px 0;
            }
        }
        .menu-add{
            display: inline-block;
            width: 90px;height: 42px;
            margin-top: 5px;margin-bottom: 30px;font-size: 15px;line-height: 42px;
            border-radius: 4px;color: #fff;text-align: center;background: #FFB31A;
            &:hover{
                cursor: pointer;
            }
        }
        .menu-img{
            position:relative;width:345px;height:195px;
            background:url("https://i1.douguo.com//upload/banner/1543312604.jpg");
            input{
                width: 100%;
                height: 100%;
                opacity: 0;
            }
            img{
                position: absolute;
                width: 100%;
                height: 100%;
                top: 0;left: 0;
                &:hover+.menu-refresh{
                    display: block;
                }
            }
            .menu-refresh{
               position: absolute;top:10px;right:10px;
               font-size: 25px;
               font-weight: bold;
               display: none;
               z-index: 5;
            }
        }
        .menu-submit{
            display: block;
            text-align: center;
            border:0;
            width: 120px;height: 40px;
            margin-top: 28px;padding: 0;
            font-size: 14px;
            line-height: 40px;
            background: #FFB31A;
            color: #fff;
            font-weight: bold;
            cursor: pointer;
            border-radius: 4px;
        }
        .menu-code{
            height: auto;line-height: 42px;overflow: hidden;
            padding: 10px 0;
            span{
                font-size: 13px;
                float: left;
            }
            input{
                width: 200px;
                height: 42px;
                float: left;
                margin-right: 10px;
            }
            .code {
                width: 114px;float: left;
                height: 40px;
                /*border: 1px solid red;*/
                &:hover{cursor: pointer;}
            }
        }
    }
}
</style>
